// import 'dart:nativewrappers/_internal/vm/lib/core_patch.dart';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../../data/local/local_storage.dart';
import '../../data/remote/home_info.dart';
import '../../generated/assets.dart';
import '../../utils/toast_utils.dart';

class RealPage extends StatefulWidget {
  const RealPage({super.key});

  @override
  State<RealPage> createState() => _RealPageState();
}

class _RealPageState extends State<RealPage> {
  final dio = Dio();
  List<Widget> ListItems = [];
  String? keywordText = '';
  TextEditingController searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    getList();
  }

  Future<void> getList() async {
    try {
      final response = await dio
          .get('http://www.cqjhzn.com/api/stat/lamp', queryParameters: {
        "keyword": keywordText,
      });
      if (response.statusCode == 200) {
        final data = response.data;
        List<Widget> list = [];
        print('data555===>${data}');

        HomeLampList? newData = HomeLampList?.fromJson(response.data);

        print('totaltotaltotal===>${newData.data!.length}');
        for (int i = 0; i < newData.data!.length; i++) {
          HomeLampData? item = newData.data?[i];
          list.add(Container(
            padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
            margin: EdgeInsets.fromLTRB(0, 0, 0, 15),
            child: Column(
              children: [
                Container(
                  margin: EdgeInsets.fromLTRB(0, 0, 0, 10),

                  // shape: RoundedRectangleBorder(
                  //     borderRadius: BorderRadius.circular(10.0)),
                  width: double.infinity,
                  decoration: BoxDecoration(
                    color: Color(0xFF192C44), // 边框
                    boxShadow: [
                      BoxShadow(
                        color: Color(0xFF059BFF),
                        blurRadius: 5,
                      ),
                    ],
                  ),
                  child: Padding(
                    padding: EdgeInsets.all(20),
                    child: Column(
                      // mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            SizedBox(
                              width: 67.5,
                              height: 28.5,
                              child: Stack(
                                children: [
                                  Image.asset(
                                    Assets.imagesNumBg,
                                    // width: 45,
                                    // height: 19,
                                    // fit: BoxFit.cover, // 根据需要选择合适的fit模式
                                  ),
                                  Align(
                                    child: Text(
                                      (i + 1).toString(),
                                      style: TextStyle(
                                          color: Color(0xFFC1C3D3),
                                          fontSize: 18,
                                          fontWeight: FontWeight.w600),
                                    ),
                                  )
                                ],
                              ),
                            ),
                            SizedBox(
                              width: 10,
                            ),
                            Text(
                              '编号：${item?.imei}',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                  fontSize: 18, color: Color(0xFFA5B2BE)),
                            ),
                          ],
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Text.rich(
                          TextSpan(
                            text: '坐标：',
                            style: TextStyle(color: Color(0xFFA5B2BE)),
                            children: <InlineSpan>[
                              TextSpan(
                                text: item?.data?.coordinates ?? '暂无',
                                style: TextStyle(color: Color(0xFFC1C3D3),fontWeight: FontWeight.bold,),
                              ),
                            ],
                          ),
                        ),

                        SizedBox(
                          height: 10,
                        ),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          // mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              '状态：',
                              style: TextStyle(color: Color(0xFFA5B2BE)),
                            ),
                            SizedBox(width: 5),
                            if (item?.statusName == '开启')
                              SizedBox(
                                width: 67.5,
                                height: 28.5,
                                child: Stack(
                                  children: [
                                    Image.asset(
                                      Assets.imagesIcStatus1,
                                      // width: 45,
                                      // height: 19,
                                      // fit: BoxFit.cover, // 根据需要选择合适的fit模式
                                    ),
                                    Positioned(
                                      top: 0,
                                      left: 20,
                                      child: Text(
                                        item!.statusName.toString(),
                                        style: TextStyle(
                                            color: Color(0xFFC1C3D3),
                                            fontWeight: FontWeight.w600),
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            if (item?.statusName == '离线')
                              SizedBox(
                                width: 67.5,
                                height: 28.5,
                                child: Stack(
                                  children: [
                                    Image.asset(
                                      Assets.imagesIcStatus2,
                                      // width: 45,
                                      // height: 19,
                                      // fit: BoxFit.cover, // 根据需要选择合适的fit模式
                                    ),
                                    Positioned(
                                      top: 0,
                                      left: 20,
                                      child: Text(
                                        item!.statusName.toString(),
                                        style: TextStyle(
                                            color: Color(0xFFC1C3D3),
                                            fontWeight: FontWeight.w600),
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            if (item?.statusName == '故障')
                              SizedBox(
                                width: 67.5,
                                height: 28.5,
                                child: Stack(
                                  children: [
                                    Image.asset(
                                      Assets.imagesIcStatus3,
                                      // width: 45,
                                      // height: 19,
                                      // fit: BoxFit.cover, // 根据需要选择合适的fit模式
                                    ),
                                    Positioned(
                                      top: 0,
                                      left: 20,
                                      child: Text(
                                        item!.statusName.toString(),
                                        style: TextStyle(
                                            color: Color(0xFFC1C3D3),
                                            fontWeight: FontWeight.w600),
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            if (item?.statusName == '关闭')
                              SizedBox(
                                width: 67.5,
                                height: 28.5,
                                child: Stack(
                                  children: [
                                    Image.asset(
                                      Assets.imagesIcStatus4,
                                      // width: 45,
                                      // height: 19,
                                      // fit: BoxFit.cover, // 根据需要选择合适的fit模式
                                    ),
                                    Positioned(
                                      top: 0,
                                      left: 20,
                                      child: Text(
                                        item!.statusName.toString(),
                                        style: TextStyle(
                                            color: Color(0xFFC1C3D3),
                                            fontWeight: FontWeight.w600),
                                      ),
                                    )
                                  ],
                                ),
                              )
                          ],
                        ),

                        SizedBox(
                          height: 10,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text.rich(
                              TextSpan(
                                text: '场地：',
                                style: TextStyle(color: Color(0xFFA5B2BE)),
                                children: <InlineSpan>[
                                  TextSpan(
                                    text: item?.unit?.name,
                                    style: TextStyle(color: Color(0xFFC1C3D3),fontWeight: FontWeight.bold,),
                                  ),
                                ],
                              ),
                            ),
                            Text.rich(
                              TextSpan(
                                text: '分类：',
                                style: TextStyle(color: Color(0xFFA5B2BE)),
                                children: <InlineSpan>[
                                  TextSpan(
                                    text: item?.lampType?.name,
                                    style: TextStyle(color: Color(0xFFC1C3D3),fontWeight: FontWeight.bold,),
                                  ),
                                ],
                              ),
                            )
                          ],
                        ),

                        SizedBox(
                          height: 10,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text.rich(
                              TextSpan(
                                text: '厂家：',
                                style: TextStyle(color: Color(0xFFA5B2BE)),
                                children: <InlineSpan>[
                                  TextSpan(
                                    text: item?.factory,
                                    style: TextStyle(color: Color(0xFFC1C3D3),fontWeight: FontWeight.bold,),
                                  ),
                                ],
                              ),
                            ),
                            Text.rich(
                              TextSpan(
                                text: '最后采集时间：',
                                style: TextStyle(color: Color(0xFFA5B2BE)),
                                children: <InlineSpan>[
                                  TextSpan(
                                    text: item?.lastUpTime,
                                    style: TextStyle(color: Color(0xFFC1C3D3),fontWeight: FontWeight.bold,),
                                  ),
                                ],
                              ),
                            )
                          ],
                        ),
                        // Text('29.12312N.108.21213E'),
                        // Text('编号：27273626262636373'),
                        if (item?.statusName == '开启'||item?.statusName == '关闭')    SizedBox(
                          height: 20,
                        ),
                        if (item?.statusName == '开启'||item?.statusName == '关闭') Divider(
                          height: 1,
                          color: Color(0xFFA5B2BE),
                        ),
                        if (item?.statusName == '开启'||item?.statusName == '关闭')  SizedBox(
                          height: 10,
                        ),
                        if (item?.statusName == '开启')
                          Center(
                              child: SizedBox(
                                  width: 180,
                                  height: 40,
                                  child: closeButton(item!.id))),

                        if (item?.statusName == '关闭')
                          Center(
                              child: SizedBox(
                                  width: 180,
                                  height: 40,
                                  child: openButton(item!.id))),
                      ],
                    ),
                  ),
                )
              ],
            ),
          ));
        }
        print('list===>${list}');
        setState(() {
          ListItems = list;
        });
      }
    } catch (e) {
      print('Error: $e');
    }
  }

  void _onSearchTextChanged(String text) {
    // 这里可以实现具体的搜索逻辑，比如过滤列表等
    setState(() {
      keywordText = text;
    });
    getList();
    // filterSearchResults(text);
  }

  void filterSearchResults(String query) {
    print('query===>$query');
    // List<String> dummySearchResult = []; // 示例数据列表，实际应用中可能是从数据库或API获取的
    // dummySearchResult = query.isEmpty
    //     ? list // 如果查询为空，显示全部数据
    //     : list.where((item) => item.toLowerCase().contains(query.toLowerCase())).toList();
    // setState(() {
    //   searchResults = dummySearchResult; // 更新UI显示结果
    // });
  }

  void onChangeLamp(id) async {
    String? token = SharedPreferencesManager().getToken();
    print('onChangeLamp-id===>$id');
    try {
      dio.options.headers.addAll({"authorization": "Bearer " + token});
      final response =
          await dio.post('http://www.cqjhzn.com/api/lamp/monitor', data: {
        "id": id,
      });
      if (response.statusCode == 200) {
        final data = response.data;
        print('data444===>${data}');

        if (response.data['code'] == 200) {
          HomeLampInfo? newData = HomeLampInfo?.fromJson(response.data);
          // print('newData===>${newData.data}');
          ToastUtils.show(newData.msg.toString());
          getList();
        } else {
          HomeLoginErrData? errData = HomeLoginErrData?.fromJson(response.data);
          print('errData===>${errData.msg}');
          ToastUtils.show(errData.msg.toString());
        }
      }
    } catch (e) {
      print('Error: $e');
    }
  }

  Widget openButton(id) {
    return TextButton(
      style: ButtonStyle(
        shape: MaterialStateProperty.all(
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(0))),
        backgroundColor: WidgetStateProperty.all<Color>(Color(0xFF3C7FB3)),
        foregroundColor: WidgetStateProperty.all<Color>(Colors.white),
        padding: WidgetStateProperty.all<EdgeInsets>(const EdgeInsets.all(10)),
      ),
      onPressed: () {
        // debugPrint('Button was pressed!');
        onChangeLamp(id);
      },
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Image.asset(
            Assets.imagesCloseLamp,
            width: 30,
            // height: 31,
          ),
          SizedBox(width: 3), // 图标和文字之间的间隔
          Text(
            '关灯',
            style: TextStyle(color: Colors.white, fontSize: 14),
          ),
        ],
      ),
    );
  }

  Widget closeButton(id) {
    return TextButton(
      style: ButtonStyle(
        shape: MaterialStateProperty.all(
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(0))),
        backgroundColor: WidgetStateProperty.all<Color>(Color(0xFF38ABB0)),
        foregroundColor: WidgetStateProperty.all<Color>(Colors.white),
        padding: WidgetStateProperty.all<EdgeInsets>(const EdgeInsets.all(10)),
      ),
      onPressed: () {
        // debugPrint('Button was pressed!');
        onChangeLamp(id);
      },
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Image.asset(
            Assets.imagesOpenLamp,
            width: 30,
            // height: 31,
          ),
          SizedBox(width: 3), // 图标和文字之间的间隔
          Text(
            '开灯',
            style: TextStyle(color: Colors.white, fontSize: 14),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: AlignmentDirectional.topCenter,
      children: [
        Image.asset(Assets.imagesHomeBg,
            width: double.infinity, height: double.infinity, fit: BoxFit.cover),
        SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: 40,
              ),
              Stack(
                // alignment:AlignmentDirectional.centerStart,
                children: [
                  Image.asset(Assets.imagesHomeTopBg,
                      width: double.infinity, fit: BoxFit.cover),
                  Center(
                    child: Image.asset(
                      Assets.imagesHomeTitle,
                      width: 130,
                      // height: 31,
                    ),
                  )
                ],
              ),
              SizedBox(
                height: 20,
              ),
              Container(
                height: 90,
                padding: EdgeInsets.fromLTRB(15, 20, 15, 20),
                child: TextField(
                  controller: searchController, // 控制搜索输入的控制器
                  style: TextStyle(
                    fontSize: 20.0, // 字体大小
                    color: Colors.white, // 字体颜色
                  ),
                  decoration: InputDecoration(
                    // labelText: '搜索',
                    // labelStyle: TextStyle(color: Color(0xFF2D8BC2)),
                    filled: true,
                    fillColor: Color(0xFF1A2B40),
                    hintText: '输入搜索内容',
                    hintStyle: TextStyle(color: Color(0xFFC1C3D3)),
                    prefixIcon: Icon(Icons.search),
                    // 搜索图标
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(2.0)),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide:
                          BorderSide(color: Color(0xFF2D8BC2)), // 激活时边框颜色为蓝色
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderSide:
                          BorderSide(color: Color(0xFF2D8BC2)), // 激活时边框颜色为蓝色
                    ),
                  ),
                  onChanged: (value) {
                    // 当文本变化时调用
                    _onSearchTextChanged(value);
                  },
                ),
              ),
              ...ListItems,
              SizedBox(
                height: 80,
              ),
            ],
          ),
        )
      ],
    );
  }
}
